package com.iptv.grape;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.github.lzyzsd.jsbridge.BridgeWebView;
import com.iptv.grape.bu.GrapeContext;
import com.iptv.grape.ui.dlg.DlgMgr;
import com.iptv.grape.domain.Channel;
import com.iptv.grape.domain.ChannelBill;
import com.iptv.grape.event.KeyEventArgs;
import com.iptv.grape.event.msg.ApkArgsData;
import com.iptv.grape.ui.control.ad.ListViewUI;
import com.iptv.grape.util.ApkUtil;
import com.iptv.grape.load_apk.LoadBack;
import com.iptv.grape.load_apk.LoadBackImp;
import com.iptv.grape.ui.dlg.LoadDlg;
import com.iptv.grape.util.AppLog;
import com.iptv.grape.util.ToastUtil;
import com.iptv.grape.util.WebViewUtils;
import com.iptv.grape.video.DefXMediaPlayerEventListener;
import com.iptv.grape.video.XMediaPlayer;


public abstract class BaseActivity extends AppCompatActivity implements LoadBackImp {
    private String thisName = this.getClass().getSimpleName();
    protected  boolean isParentEvent = true;

    //0 = 7
    //1 = 8
    //2 = 9
    //9 = 16
    // UP = 19
    // DOWN = 20
    // R = 22
    // LEFT = 21
    // Enter = 66
    // BACK = 4
    // 返回 true 或 false
    // 上一级将根据 DecorView 返回 true 的结果停止焦点的移动
    // 那么上一级会继续执行焦点移动的逻辑，表现出来的效果就是，界面上的焦点仍然会移动
    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        //public static final int KEYCODE_BACK            = 4;
        //Log.e("activity","dispatchKeyEvent");
        if(!isParentEvent)
            return super.dispatchKeyEvent(event);
        if (GrapeContext.curGrapeContext().isFocus()) {
            //AppLog.getCurLog().out("BaseActivity App Proc Key" + event.getKeyCode());
            return super.dispatchKeyEvent(event);
        }
        if (event.getAction() != KeyEvent.ACTION_UP) {
            int code = KeyEvent.KEYCODE_BACK;
            AppLog.getCurLog().out(event.getKeyCode());
//            if(code == 46){
//                ActivityManager manager = (ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
//                manager.restartPackage("com.iptv.grape");
//            }

            if (KeyEventArgs.containsKey(event.getKeyCode())) {
                String json = KeyEventArgs.getKeyEventArgs(event.getKeyCode());
                WebViewUtils.sentKeyMessageToWebView(json, this.getBridgeWebView());

                //new ExecSendH5Thread(event.getKeyCode()).start();
                AppLog.getCurLog().out("Send To H5:");
                return true;
            }
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppLog.getCurLog().e("activity====>" + thisName);
        LoadBack.ISTC().setLoadBack(this);
    }


    class ExecSendH5Thread extends Thread {
        private int keyCode;

        public ExecSendH5Thread(int keyCode) {
            this.keyCode = keyCode;
        }

        @Override
        public void run() {
            BaseActivity.this.sendH5(keyCode);
        }
    }

    private void sendH5(int keyCode) {
        String json = KeyEventArgs.getKeyEventArgs(keyCode);
        WebViewUtils.sentKeyMessageToWebView(json, BaseActivity.this.getBridgeWebView());
    }

    public BridgeWebView getBridgeWebView() {
        return null;
    }

    public XMediaPlayer getXMediaPlayer() {
        return null;
    }

    // 显示右上角直播的标题
    public void showTopTitle(String channelName, String typeText) {

    }

    // 显示右上角直播的标题
    public void showTopTitleDelayedClose(String channelName, String typeText, ChannelBill nowChannelBill,
                                         ChannelBill nextChannelBill) {

    }

    public void cancelHideTopTitleHandler() {

    }

    // 隐藏右上角直播的标题
    public void hideTopTitle() {

    }

    // 显示换台的界面
    public void showChangingLiveUI() {

    }

    // 设置用户输入的频道号
    public void setChangingLiveNo(String num) {

    }

    // 隐藏换台的界面
    public void hideChangingLiveUI() {

    }

    // 没有找到频道号时
    public void NoFindNo() {
        //changingCenter.setText(num);
    }

    public void statuVisible(String name,String type){

    }
    public void statuVisible(){

    }
    public void statuGone(){

    }
    public void visibles(){

    }


    // 弹出节目单的预约
    public void showChannelBill(Channel channel, ChannelBill channelBill, boolean isAppointment, ListViewUI listViewUI) {

    }

    // 弹出预约提醒
    public void showAppointmentReminder(Channel channel, ChannelBill channelBill) {

    }

    // 显示暂停按钮
    public void showPause() {
        this.findViewById(R.id.pause_layout).setVisibility(View.VISIBLE);
    }

    // 隐藏暂停按钮
    public void hidePause() {
        this.findViewById(R.id.pause_layout).setVisibility(View.GONE);
    }

    public Handler getmHandler() {
        return null;
    }

    public DefXMediaPlayerEventListener getDefXMediaPlayerEventListener() {
        return null;
    }


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        if (newConfig.fontScale != 1)//非默认值
            getResources();
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        if (res.getConfiguration().fontScale != 1) {//非默认值
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults();//设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }

    public void showAdImg() {

    }

    public void hideAdImg() {

    }

    private LoadDlg mDlg;
    @Override
    public void loadApk(ApkArgsData apkArgsData) {
        final String name = apkArgsData.getAppName();
        final String url = apkArgsData.getUrl();
        final int size = apkArgsData.getSize();
        String packageName = apkArgsData.getPackageName();

        boolean isInstance = ApkUtil.isInstallApp(this,packageName);
        if(isInstance){
            PackageManager packageManager = getPackageManager();
            Intent it = packageManager.getLaunchIntentForPackage(packageName);
            if (it != null){
                startActivity(it);
            }else{
                ToastUtil.show("未找到跳转应用入口！");
            }
        }else{
            DlgMgr.cfmDlg(this, "未找到应用，是否去下载？", new DlgMgr.Click() {
                @Override
                public void onListener(View view) {
                    switch (view.getId()){
                        case R.id.btnOk:
                            mDlg = new LoadDlg(BaseActivity.this,url,name,size);
                            mDlg.show();
                            break;
                    }
                }
            });

        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(null!=mDlg&&mDlg.isShowing()){
            mDlg.dismiss();
        }
        DlgMgr.cancel();
    }
}
